package org.future.persistent.id;
/**
 * 生成 uuid
 * @author dycc
 * @date 2009-12-30 下午03:19:07
 */
public class HexUUID extends UUIDGenerator{
    
    public HexUUID(){
        
    }    
    /**
     * 返回32位的主键
     * @return
     */
    public String getId32(){
        return getId(32);
    }
    /**
     * 返回指定长度的主键
     * @param charNumber
     * @return
     */
    public String getId(int length){
        String id = generate();  
        int start = id.length() - length;
        if(start < 0){
            start = 0;
        }
        id = id.substring(start);
        return id;
    }
    /**
     * 生成 [32,36]位的主键
     * @return
     */
    public String generate(){
        StringBuffer sb = new StringBuffer(36);  // 32位字符 + 4位分隔符
        sb.append(formatInt(getIp())).append(getSeparator())         // 8
        .append(formatInt(getJvm())).append(getSeparator())          // 8
        .append(formatShort(getHighTime())).append(getSeparator())   // 4
        .append(formatInt(getLowerTime())).append(getSeparator())    // 8
        .append(formatShort(getCounter()));                          // 4
        return sb.toString().toUpperCase();
    }
    /**
     * 将 intVal格式化为 前缀为0,length 为8的String
     * hexStr.length() <= 8 [int32 -> hex8]
     * @param intVal
     * @return
     */
    private String formatInt(int intVal){
        String hexStr = Integer.toHexString(intVal);   
        StringBuffer buf = new StringBuffer("00000000");
        int start = 8 - hexStr.length();                             // >= 0
        buf.replace(start, 8, hexStr);
        return buf.toString();
    }
    /**
     * 将shortVal格式为前缀0,length为4的String
     * hexStr.length() <= 4 [short16 -> hex4]
     * @param shortVal
     * @return
     */
    private String formatShort(short shortVal){
        String hexStr = Integer.toHexString(shortVal);   
        StringBuffer buf = new StringBuffer("0000");
        int start = 4 - hexStr.length();                             // >= 0
        buf.replace(start, 4, hexStr);
        return buf.toString();
    }    
}
